package com.java.baseconversion;

import org.junit.Test;

/**
 * 字符串转化为16进制
 * 16进制转化为字符串
 * @author wangning
 * @create 2022-04-01 14:37
 */
public class Test01 {
	//	String str = "鲸";
	String str = "abc";
	@Test
	public void test01() {
		char[] chars = "0123456789abcdef".toCharArray();
		StringBuilder builder = new StringBuilder("");
		byte[] bs = str.getBytes();
		int bit;
		for (byte b : bs) {
			bit = (b & 0x0f0) >> 4;
			builder.append(chars[bit]);
			bit = b & 0x0f;
			builder.append(chars[bit]);
			builder.append(' ');
		}
		System.out.println(builder.toString().trim());
	}

	@Test
	public void test02() {
		byte[] bytes = str.getBytes();
		for (byte aByte : bytes) {
			String hexString = Integer.toHexString(0xFF & aByte);
			if (hexString.length() == 1) {
				hexString = "0" + hexString;
			}
			System.out.println(hexString);
		}
	}

	@Test
	public void test03() {
		byte[] bytesArr = str.getBytes();
		for (byte b : bytesArr) {
			String hexStr = Integer.toHexString(0xFF & b);
			System.out.println(hexStr);
		}

	}

	/**
	 * 字符串转换成为16进制(无需Unicode编码)
	 * @param str
	 * @return
	 */
	public static String str2HexStr(String str) {
		char[] chars = "0123456789ABCDEF".toCharArray();
		StringBuilder sb = new StringBuilder("");
		byte[] bs = str.getBytes();
		int bit;
		for (int i = 0; i < bs.length; i++) {
			bit = (bs[i] & 0x0f0) >> 4;
			sb.append(chars[bit]);
			bit = bs[i] & 0x0f;
			sb.append(chars[bit]);
			// sb.append(' ');
		}
		return sb.toString().trim();
	}


	/**
	 * 16进制转化为字符串
	 */
	@Test
	public void test04() {
		byte[] bytes = str.getBytes();
		String hexString = "";
		String hex = "";
		for (byte aByte : bytes) {
			hexString = Integer.toHexString(0xFF & aByte);
			if (hexString.length() == 1) {
				hexString = "0" + hexString;
			}
			hex += hexString;
		}
		System.out.println("hex = " + hex);

		String str11 = "0123456789ABCDEF";
		char[] hexs = hex.toCharArray();
		byte[] b = new byte[hex.length() / 2];
		int n;
		for (int i = 0; i < bytes.length; i++) {
			n = str11.indexOf(hexs[2 * i]) * 16;
			n += str11.indexOf(hexs[2 * i + 1]);
			b[i] = (byte) (n & 0xff);
		}
		System.out.println(new String(b));


	}
}
